package io.bdmc.common.wechatsdk;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.bdmc.common.http.HttpClientUtil;
import io.bdmc.common.http.HttpResult;
import io.bdmc.common.utils.Constant;
import io.bdmc.common.utils.RedisUtils;
import io.bdmc.modules.bss.entity.SmkMessage;

@Service
public class TemplateMsgUtil {
    @Resource
    private RedisUtils _redis;

    @Autowired
    private HttpClientUtil _httpCLient;

    protected Logger logger = LoggerFactory.getLogger(getClass());
    // 微信模板消息发送接口地址
    private final String SEND_TEMPLAYE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
  
    private void sendTemplateMessage( WechatTemplate wechatTemplate) {
        String jsonString = JSONObject.toJSONString(wechatTemplate);     
        AccessToken accessToken = WeChatUtil.getAccessToken();
        if(accessToken==null){
            logger.info("access token获取失败");
            return;
        }
        String requestUrl = SEND_TEMPLAYE_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken.getToken());
        HttpResult re;
        try {
            re = _httpCLient.doPostJson(requestUrl, jsonString);
            JSONObject weiXinResponse = JSONObject.parseObject(re.getBody());
            if (null != weiXinResponse) {
                int errorCode = weiXinResponse.getInteger("errcode");
                if (0 == errorCode) {
                    logger.info("模板消息发送成功");
                } else {
                    String errorMsg = weiXinResponse.getString("errmsg");
                    logger.info("模板消息发送失败,错误代码是 " + errorCode + ",错误信息是" + errorMsg);
                }
                SmkMessage msglog = new SmkMessage();
                msglog.setMsgMobile(wechatTemplate.getTouser());
                msglog.setMsgType(3);
                msglog.setResultCode( weiXinResponse.getString("errcode"));
                msglog.setResultMsg( weiXinResponse.getString("errmsg"));
                msglog.setJoinDate(LocalDateTime.now());
                Map<String,TemplateData> m = wechatTemplate.getData();
                String d = JSONObject.toJSONString( m.get("first").getValue());
                msglog.setMsgDetail(d);
                msglog.insert();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

    }

    public void sendWXAlarmMsg(String[] openids,String dataTime,String shopName,String imei,String devName,String alarmType,String alarmDetail,
    String addr,String managerName,String managerMobile,String url){
        WechatTemplate w = new WechatTemplate();
        w.setTemplate_id(Constant.TEMPLATEID1);
        w.setUrl(url);
        //w.setTouser(openid);
        Map<String,TemplateData> m = new HashMap<String,TemplateData>();
        TemplateData first = new TemplateData();
        if(alarmType.equals("火警")){
            first.setColor("#FF0000");
        }else{
            first.setColor("#EE7600");
        }
        first.setValue(alarmDetail);
        m.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setColor("#000000");
        keyword1.setValue(shopName+imei);
        m.put("keyword1", keyword1);
        TemplateData keyword2 = new TemplateData();
        keyword2.setColor("#000000");
        keyword2.setValue(managerName);
        m.put("keyword2", keyword2);
        TemplateData keyword3 = new TemplateData();
        keyword3.setColor("#000000");
        keyword3.setValue(managerMobile);
        m.put("keyword3", keyword3);
        TemplateData keyword4 = new TemplateData();
        keyword4.setColor("#000000");
        keyword4.setValue(devName+"-"+alarmType);
        m.put("keyword4", keyword4);
        TemplateData keyword5 = new TemplateData();
        keyword5.setColor("#000000");
        keyword5.setValue(dataTime);
        m.put("keyword5", keyword5);

        TemplateData remark = new TemplateData();
        remark.setColor("#000000");
        remark.setValue("请及时前往"+addr+"确认并处理。");
        m.put("remark", remark);
        w.setData(m);
        for (String openid : openids) {
            w.setTouser(openid);
            sendTemplateMessage(w);
        }
    }

    public void sendWXAlarmCleanMsg(String[] openids,String dataTime,String shopName,String imei,String devName,String alarmType,String alarmDetail,
            String managerName,String managerMobile){
        if(openids.length<1){
            logger.info("未绑定微信号，无法推送");
            return;
        }
        WechatTemplate w = new WechatTemplate();
        w.setTemplate_id(Constant.TEMPLATEID1);
        Map<String,TemplateData> m = new HashMap<String,TemplateData>();
        TemplateData first = new TemplateData();
        first.setColor("#458B00");
        first.setValue(alarmDetail);
        m.put("first", first);
        TemplateData keyword1 = new TemplateData();
        keyword1.setColor("#000000");
        keyword1.setValue(shopName+imei);
        m.put("keyword1", keyword1);
        TemplateData keyword2 = new TemplateData();
        keyword2.setColor("#000000");
        keyword2.setValue(managerName);
        m.put("keyword2", keyword2);
        TemplateData keyword3 = new TemplateData();
        keyword3.setColor("#000000");
        keyword3.setValue(managerMobile);
        m.put("keyword3", keyword3);
        TemplateData keyword4 = new TemplateData();
        keyword4.setColor("#000000");
        keyword4.setValue(devName);
        m.put("keyword4", keyword4);
        TemplateData keyword5 = new TemplateData();
        keyword5.setColor("#000000");
        keyword5.setValue(dataTime);
        m.put("keyword5", keyword5);

        TemplateData remark = new TemplateData();
        remark.setColor("#000000");
        remark.setValue("告警已解除。");
        m.put("remark", remark);
        w.setData(m);
        for (String openid : openids) {
            w.setTouser(openid);
            sendTemplateMessage(w);
        }
    }
}